package cn.tedu.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadPoolDemo02 {
    /**核心线程数*/
    static final int corePoolSize = 2;
    /**最大线程数*/
    static final int maximumPoolSize = 3;
    /**线程空闲时间*/
    static final long keepAliveTime = 60;
    /**时间单位*/
    static final TimeUnit unit = TimeUnit.SECONDS;
    /**存储任务的阻塞式队列*/
    static final BlockingQueue<Runnable> workQueue =
            new ArrayBlockingQueue<>(1);
    /**创建线程的工厂
     * 基于此对象获取自增值
     */
    static AtomicLong atomicLong = new AtomicLong(1);
    static final ThreadFactory threadFactory =(Runnable r)-> {
        return new Thread(r,
                "service-task-"+atomicLong.getAndIncrement());
    };
    /**拒绝策略*/
    static final RejectedExecutionHandler handler =
            new ThreadPoolExecutor.AbortPolicy();//丢弃并抛出异常
            //new ThreadPoolExecutor.CallerRunsPolicy();//由调用者执行任务
            //new ThreadPoolExecutor.DiscardOldestPolicy();//丢弃最早的任务
            //new ThreadPoolExecutor.DiscardPolicy();//直接丢弃当前任务
    public static void main(String[] args) {
        //线程池创建:重点理解七大入参
        ThreadPoolExecutor executor=
        new ThreadPoolExecutor(
                corePoolSize,//池中要维持的线程数量，初始是0
                maximumPoolSize,//最多有多少个线程
                keepAliveTime,//线程空闲时间
                unit,//时间单位
                workQueue,//阻塞式工作队列
                threadFactory,//线程工厂，用于创建池中需要的线程
                handler);//拒绝策略(池达到最大吞吐量后，再来任务怎么办)
        for (int i = 0; i < 5; i++) {
            executor.execute(()->{
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName+"->task:"+System.currentTimeMillis());
                try{Thread.sleep(1000);}catch (InterruptedException e){}
            });
        }
        executor.shutdown();
    }
}
